﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Linq;

namespace Module_Debug
{
    public partial class Form_Make_a_picture : Form
    {
        public Form_Make_a_picture(frmMain Frm)
        {
            MainForm = Frm;
            InitializeComponent();
        }
        frmMain MainForm = null;
        private IWorkbook wk;
        private FileStream fs;
        string[,] strnum_input;
        string[,] strnum;
        string pic_name = null;

        private void Form_Make_a_picture_FormClosing(object sender, FormClosingEventArgs e)
        {
            frmMain.frmain.Make_a_picture_form = null;
        }
        private void Makebmp_Click(object sender, EventArgs e)
        {
            try
            {
                switch (tabControl1.SelectedIndex)
                {
                    case 0://边框图
                        {
                            MakePixelmap();
                        }
                        break;
                    case 1://
                        {
                            MakeLogicDiagram();
                        }
                        break;

                }
            }
            catch { MessageBox.Show("参数设置错误！！！"); }
        }
        private void MakePixelmap()
        { 
            Color c0=Color.FromArgb((int)HFZ_M_R.Value,(int)HFZ_M_G.Value,(int)HFZ_M_B.Value);//底色
            Color c1 = Color.FromArgb((int)HFZ_L_R.Value, (int)HFZ_L_G.Value, (int)HFZ_L_B.Value);//局部色
            Bitmap BmpOut = new Bitmap((int)H_size.Value, (int)V_size.Value, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            Graphics g = Graphics.FromImage(BmpOut);
            g.FillRectangle(new SolidBrush(c0), 0, 0, BmpOut.Width, BmpOut.Height);
            int i;int j;int k;

            for (i = 0; i < strnum.GetLength(0); i++)
            {
                for (j = 0; j < strnum.GetLength(1); j++)
                {
                    if (strnum[i, j] == "1")
                    {
                        if (j + frame_width.Value >= strnum.GetLength(1) || j - frame_width.Value < 0 || i + frame_width.Value >= strnum.GetLength(0) || i - frame_width.Value < 0)
                        {
                            BmpOut.SetPixel(j, i, c1);
                            continue;
                        }
                        for (k = 1; k <= frame_width.Value; k++)
                        {
                            if (strnum[i, j + k] != "1" || strnum[i, j - k] != "1" || strnum[i + k, j] != "1" || strnum[i - k, j] != "1")
                            {
                                BmpOut.SetPixel(j, i, c1);
                                continue;
                            }
                        }
                    }
                }
            }

            BmpShow.Image = BmpOut;
        }
        private void OpenExcel(string path)//NPIO打开excel
        {
            try
            {
                using (fs = File.OpenRead(path))   //打开myxls.xls文件
                {
                    wk = new XSSFWorkbook(fs);   //把xls文件中的数据写入wk中

                    for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中总共的表数
                    {
                        ISheet sheet = wk.GetSheetAt(i);   //读取当前表数据
                        for (int j = 0; j <= sheet.LastRowNum; j++)  //LastRowNum 是当前表的总行数
                        {
                            IRow row = sheet.GetRow(j);  //读取当前行数据
                            if (checkBox2.Checked == true)//分辨率核验
                            {
                                if (sheet.LastRowNum != (int)V_size.Value-1+ num_height1.Value)
                                {
                                    MessageBox.Show("V分辨率设置与pixelmap不符，请检查");
                                    return;
                                }
                                if (j == 0&& (row.LastCellNum != (int)H_size.Value * 3 + num_width1.Value && row.LastCellNum != (int)H_size.Value + num_width1.Value && row.LastCellNum != (int)H_size.Value * 2 + num_width1.Value)) 
                                {
                                    MessageBox.Show("H分辨率设置与pixelmap不符，请检查");
                                    return;
                                }
                            }
                            if (j == 0)
                            {
                                strnum_input = new string[(int)V_size.Value + (int)num_height1.Value, row.LastCellNum];
                            }
                            if (row != null)
                            {
                                for (int k = 0; k <= row.LastCellNum; k++)  //LastCellNum 是当前行的总列数
                                {
                                    ICell cell = row.GetCell(k);  //当前表格
                                    if (cell != null)
                                    {
                                        strnum_input[j,k]= Convert.ToString(cell);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("文件被其他应用打开，请关闭对该文件的引用！！！");
            }

        }
        private void Open_CSV(string path)
        {
            try
            {
                int line_count = 0;
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string strLine = streamReader.ReadLine();
                string[] aab = strLine.Split(',');
                if (checkBox2.Checked == true)
                {
                    if (aab.Length != (int)H_size.Value + (int)num_height1.Value)
                    {
                        MessageBox.Show("H分辨率设置与pixelmap不符，请检查");
                        return;
                    }
                }
                strnum_input = new string[(int)V_size.Value + (int)num_height1.Value, aab.Length];
                while (!string.IsNullOrEmpty(strLine))
                {
                    aab = strLine.Split(',');
                    for(int i = 0; i < aab.Length; i++)
                    {
                        strnum_input[line_count, i] = aab[i];
                    }
                    strLine = streamReader.ReadLine(); //循环读取下一行
                    line_count++;
                    if(line_count> (int)V_size.Value + (int)num_width1.Value)
                    {
                        MessageBox.Show("V分辨率设置与pixelmap不符，请检查");
                        return;
                    }
                }
                fs.Close(); //关闭流
                streamReader.Close();
                if (checkBox2.Checked)
                {
                    if (line_count != (int)V_size.Value + (int)num_width1.Value)
                    {
                        MessageBox.Show("V分辨率设置与pixelmap不符，请检查");
                        return;
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("文件被其他应用打开，请关闭对该文件的引用！！！");
            }
        }
        private void check_HVACT()//原始数据脱水
        {
            strnum = new string[(int)V_size.Value,(int)H_size.Value];
            int k = 0;
            int i=0;
            int j=0;
            try
            {
                for (i = (int)num_height1.Value; i < strnum_input.GetLength(1);)
                {
                    for (j = (int)num_width1.Value; j < strnum_input.GetLength(0); j++)
                    {
                        if (strnum_input[j, i] != null)
                        {
                            strnum[j-1, k] = "1";
                        }
                    }
                    if (strnum_input.GetLength(1) == (int)H_size.Value + num_height1.Value)
                    {
                        i++;
                    }
                    else if (strnum_input.GetLength(1) == (int)H_size.Value * 2 + num_height1.Value)
                    {
                        i = i + 2;
                    }
                    else if (strnum_input.GetLength(1) == (int)H_size.Value * 3 + num_height1.Value)
                    {
                        i = i + 3;
                    }
                    k++;
                }
            }
            catch
            {
                MessageBox.Show(i+";"+j+";"+k);
            }
            
            //strnum_input = new string[1,1];
        }
        private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;//设定只允许打开一个文件

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.Text += openFileDialog.FileName;
                string Alastname = openFileDialog.FileName.Substring(openFileDialog.FileName.LastIndexOf(".")+1).ToUpper();
                var filePath = openFileDialog.FileName;//
                pic_name = openFileDialog.SafeFileName.Substring(0, openFileDialog.SafeFileName.LastIndexOf("."));
                if (string.IsNullOrEmpty(filePath)) return;//判断选择的文件名称是不是空
                try
                {
                    if (Alastname == "BMP")
                    {
                        Image BMPPixelmap = Bitmap.FromFile(openFileDialog.FileName);
                        H_size.Value = BMPPixelmap.Width;
                        V_size.Value = BMPPixelmap.Height;
                        BmpShow.Image = (Bitmap)BMPPixelmap;
                    }
                    else if (Alastname == "CSV")
                    {
                        Open_CSV(openFileDialog.FileName);
                        check_HVACT();
                    }
                    else if (Alastname == "XLSX")
                    {
                        OpenExcel(openFileDialog.FileName);
                        check_HVACT();
                    }
                    else
                    {
                        MessageBox.Show("选中的" + Alastname + "格式不在兼容范围内");
                    }
                    MessageBox.Show("数据载入完成");
                }
                catch
                {
                    MessageBox.Show("打开文件失败");
                }
            }
            else
            {
                return;
            }
        }
        private void SaveBmp_Click(object sender, EventArgs e)//保存
        {
            Bitmap clone;
            Bitmap box = new Bitmap(Convert.ToInt16(H_size.Text), Convert.ToInt16(V_size.Text));          
            SaveFileDialog sv1 = new SaveFileDialog
            {
                Filter = "bmp|*.bmp"
            };
            sv1.FileName = pic_name;
            sv1.ShowDialog();
            string str = sv1.FileName;
            if (checkBox1.Checked == true)
            {
                clone = box.Clone(new Rectangle(0, 0, Convert.ToInt16(H_size.Text), Convert.ToInt16(V_size.Text)), System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
            }
            else
                clone = box.Clone(new Rectangle(0, 0, Convert.ToInt16(H_size.Text), Convert.ToInt16(V_size.Text)), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            using (Graphics g = Graphics.FromImage(clone))
            {
                if (BmpShow.Image.Width != Convert.ToInt16(H_size.Text))
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(BmpShow.Image, new Rectangle(0, 0, Convert.ToInt16(H_size.Text), Convert.ToInt16(V_size.Text)));
            }
            try
            {
                clone.Save(str, System.Drawing.Imaging.ImageFormat.Bmp);
                MessageBox.Show("保存成功");
            }
            catch
            {
                MessageBox.Show("保存失败！！");
            }
        }
        private void Form_Make_a_picture_Load(object sender, EventArgs e)
        {
            H_size.Value = frmMain.frmain.HACT.Value;
            V_size.Value= frmMain.frmain.VACT.Value;
        }
        private void MakeLogicDiagram ()
        {
            Color c0 = Color.FromArgb((int)HFZ_M_R.Value, (int)HFZ_M_G.Value, (int)HFZ_M_B.Value);//底色
            Color c1 = Color.FromArgb((int)HFZ_L_R.Value, (int)HFZ_L_G.Value, (int)HFZ_L_B.Value);//局部色
            Bitmap BmpOut = new Bitmap((int)H_size.Value, (int)V_size.Value, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            Graphics g = Graphics.FromImage(BmpOut);
            g.FillRectangle(new SolidBrush(c0), 0, 0, BmpOut.Width, BmpOut.Height);

            switch (logicdiagramBox.SelectedIndex)
            {
                case 0: //dot 等分 棋盘格
                    {
                        DotCheckerboard(BmpOut,c0, c1);
                    }
                    break;
                case 1: //灰阶过渡
                    {
                        GrayTransition(BmpOut,c0, c1);
                    }
                    break;
                case 2: //灵动岛灰阶挖孔
                    {
                        PixelmapSave(BmpOut, c0, c1);
                    }
                    break;
                case 3: //灵动岛彩图挖孔
                    {
                        BMPPixelmapSave(BmpOut,c0);
                    }
                    break;
            }

            BmpShow.Image = BmpOut;

        }
        private void DotCheckerboard(Bitmap BmpOut,Color c0, Color c1)
        {
            try
            {
                string str = dotnums.Text;
                string[] splitString = str.Split(','); // 分割字符串
                int[] Dotarray = Array.ConvertAll(splitString, int.Parse); // 转换为int数组

                int Dotlength = Dotarray.Length;
                int[] DotHeight = new int [Dotlength+1];
                for (int i = 0; i < Dotlength + 1; i++)
                {
                   DotHeight[i] = i * BmpOut.Height / Dotlength - 1;
                }

                for (int i = 0; i < Dotlength; i++)
                {
                    for (int h = DotHeight[i] + 1; h < DotHeight[i + 1] + 1; h++)
                    {
                        for (int j = 0; j < BmpOut.Width; j++)
                        {
                            if ((((h - DotHeight[i]) + Dotarray[i] - 1) / Dotarray[i]) % 2 == ((j + Dotarray[i]) / Dotarray[i]) % 2)
                            {
                                BmpOut.SetPixel(j, h, c1);
                            }
                            else
                            {
                                BmpOut.SetPixel(j, h, c0);
                            }
                        }
                    }
                }
            }
            catch
            {
                MessageBox.Show("dot 输入格式有误，参考 1,2,4 。横向3等分棋盘格，尺寸 = 1x1 : 2x2 : 4x4 ");
            }
        }
        private void GrayTransition(Bitmap BmpOut, Color c0, Color c1)
        {
            int verticalResolution = BmpOut.Width;
            int horizontalResolution = BmpOut.Height;

            for (int y = 0; y < horizontalResolution; y++)

            {
                Color rowColor = GetInterpolatedColor(c0, c1, y, horizontalResolution);

                for (int x = 0; x < verticalResolution; x++)
                {
                    BmpOut.SetPixel(x, y, rowColor);
                }
            }
        }
        private void PixelmapSave(Bitmap BmpOut, Color c0, Color c1)
        {
            Graphics g = Graphics.FromImage(BmpOut);
            g.FillRectangle(new SolidBrush(c0), 0, 0, BmpOut.Width, BmpOut.Height);
            int i; int j; int k;

            for (i = 0; i < V_size.Value; i++)
            {
                for (j = 0; j < H_size.Value; j++)
                {
                    if (strnum_input[i, j] == "1")
                    {
                        BmpOut.SetPixel(j, i, c1);
                    }
                    else
                    {
                        BmpOut.SetPixel(j, i, c0);
                    }
                }
            }

            BmpShow.Image = BmpOut;
        }
        private Color GetInterpolatedColor(Color start, Color end, int currentY, int totalHeight)
        {
            double factor = (totalHeight == 1) ? 0.5 : (double)currentY / (totalHeight - 1);

            int r = InterpolateChannel(start.R, end.R, factor);
            int g = InterpolateChannel(start.G, end.G, factor);
            int b = InterpolateChannel(start.B, end.B, factor);

            return Color.FromArgb(r, g, b);
        }
        private int InterpolateChannel(byte startVal, byte endVal, double factor)
        {
            double value = startVal + (endVal - startVal) * factor;
            return Clamp((int)Math.Round(value), 0, 255);
        }
        private int Clamp(int value, int min, int max)
        {
            return Math.Max(min, Math.Min(value, max));
        }
        private void Load_BMP_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;//设定只允许打开一个文件

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.Text += openFileDialog.FileName;
                string Alastname = openFileDialog.FileName.Substring(openFileDialog.FileName.LastIndexOf(".") + 1).ToUpper();
                var filePath = openFileDialog.FileName;//
                pic_name = openFileDialog.SafeFileName.Substring(0, openFileDialog.SafeFileName.LastIndexOf("."));
                if (string.IsNullOrEmpty(filePath)) return;//判断选择的文件名称是不是空
                try
                {
                    if (Alastname == "BMP")
                    {
                        Image Bmpint = Bitmap.FromFile(openFileDialog.FileName);
                        H_size.Value = Bmpint.Width;
                        V_size.Value = Bmpint.Height;
                        BmpShow2.Image = (Bitmap)Bmpint;
                    }
                    else
                    {
                        MessageBox.Show("选中的" + Alastname + "格式不在兼容范围内");
                    }
                    MessageBox.Show("数据载入完成");
                }
                catch
                {
                    MessageBox.Show("打开文件失败");
                }
            }
            else
            {
                return;
            }
        }
        private void BMPPixelmapSave(Bitmap BmpOut, Color c0)
        {
            if (BmpShow?.Image == null || BmpShow2?.Image == null)
            {
                MessageBox.Show("源图像不能为空");
                return;
            }
            Bitmap BMPPixelmap = (Bitmap)BmpShow.Image;
            Bitmap BMPint = (Bitmap)BmpShow2.Image;

            if (BMPPixelmap.Width != (int)H_size.Value || BMPPixelmap.Height != (int)V_size.Value ||BMPint.Width != (int)H_size.Value || BMPint.Height != (int)V_size.Value)
            {
                MessageBox.Show("图像尺寸与设置的分辨率不匹配");
                return;
            }
            for (int i = 0; i < (int)V_size.Value; i++)
            {
                for (int j = 0; j < (int)H_size.Value; j++)
                {
                    if (BMPPixelmap.GetPixel(j, i).ToArgb() == c0.ToArgb())
                    {
                        BmpOut.SetPixel(j, i, c0);
                    }
                    else
                    {
                        BmpOut.SetPixel(j, i, BMPint.GetPixel(j, i));
                    }
                }
            }
            BmpShow.Image = BmpOut;
        }

    }
}
